package com.gitlab.bootren.data.core.query;

import com.gitlab.bootren.data.core.query.restriction.RestrictionType;

import java.util.HashMap;
import java.util.Map;

/**
 * 条件基类
 *
 * @author tengda
 *
 */
public abstract class AbstractCondition implements ICondition {

    protected Map<String, Object> params = new HashMap<String, Object>();

    @Override
    public ICondition setParam(String paramName, Object object) {
        params.put(paramName.replaceAll("\\.", "_"), object);
        return this;
    }

    @Override
    public ICondition and(ICondition conditionModel) {
        if (conditionModel == null) {
            return this;
        }
        return new CombCondition(this, conditionModel);
    }

    @Override
    public ICondition and(String key, Object value) {
        return this.and(new KvCondition(key, value));
    }

    @Override
    public ICondition and(String key, Object value, RestrictionType restrictionType) {
        return this.and(new KvCondition(key, value, restrictionType));
    }

    @Override
    public ICondition and(String jpql) {
        return this.and(new QlCondition(jpql));
    }

    @Override
    public ICondition or(ICondition conditionModel) {
        if (conditionModel == null) {
            return this;
        }
        return new CombCondition(this, conditionModel, CombType.OR);
    }

    @Override
    public ICondition or(String key, Object value) {
        return this.or(new KvCondition(key, value));
    }

    @Override
    public ICondition or(String key, Object value, RestrictionType restrictionType) {
        return this.or(new KvCondition(key, value, restrictionType));
    }

    @Override
    public ICondition or(String jpql) {
        return this.or(new QlCondition(jpql));
    }

    @Override
    public ICondition setParams(Map<String, Object> params) {

        this.params.putAll(params);
        return this;
    }

    @Override
    public Map<String, Object> getParams() {
        return this.params;
    }

    public String replaceAlias(String ql, String alias) {
        if (alias == null) {
            return ql;
        }
        alias = alias.trim();
        if (alias.length() == 0) {
            return ql.replaceAll("this.", "");
        }
        return ql.replaceAll("this.", alias + ".");
    }

    @Override
    public String toString() {
        return this.toQl();
    }


    @Override
    public String toQl() {
        String ql = this.ql().trim();

        return ql;

    }

    @Override
    public String toQl(String aliasName) {
        String ql = this.ql(aliasName).trim();
        return ql;
    }

    protected abstract String ql();

    protected abstract String ql(String aliasName);
}
